package com.immer.session;

import org.springframework.data.redis.core.RedisTemplate;

import java.util.Set;
import java.util.UUID;

public class RedisSessionClient {

    /**
     * redis zset 存储sessionid 集合，设置过期时间score
     */
    private static final String SESSION_REDIS_ID_ZSET_KEY = "session-id-zset-key";

    /**
     * redis hash key
     */
    private static final String SESSION_REDIS_KEY = "session-key";

    /**
     * redis session id 有序增长
     */
    private static final String SESSION_AES_KEY = "session-id-aes-key";


    private RedisTemplate redisTemplate;

    public RedisSessionClient(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    public RedisSession get(String sessionId) {
        Double score = redisTemplate.opsForZSet().score(SESSION_REDIS_ID_ZSET_KEY, sessionId);
        if (score != null && score >= 0) {
            return (RedisSession) redisTemplate.opsForHash().get(SESSION_REDIS_KEY, sessionId);
        }
        return null;
    }

    /**
     * 此处redis 5分钟检测
     */
    public void set(Long expTime, RedisSession session) {
        Boolean addFlag = redisTemplate.opsForZSet().add(SESSION_REDIS_ID_ZSET_KEY, session.getId(), expTime);
        if (null != addFlag && addFlag) {
            redisTemplate.opsForHash().put(SESSION_REDIS_KEY, session.getId(), session);
        }
    }

    public void delete(String sessionId) {
        System.out.println("删除 sessionId : " + sessionId);
        redisTemplate.opsForZSet().remove(SESSION_REDIS_ID_ZSET_KEY, sessionId);
        redisTemplate.opsForHash().delete(SESSION_REDIS_KEY, sessionId);
    }


    public String createSessionId() {
        Long id = redisTemplate.opsForValue().increment(SESSION_AES_KEY, 1);
        return UUID.randomUUID().toString().replace("-", "").toUpperCase().substring(15) + id;
    }


    public Set rangeSessionSet(Long start, Long end) {
        return redisTemplate.opsForZSet().rangeByScore(SESSION_REDIS_ID_ZSET_KEY, start, end);
    }

}
